package com.dp.temp;

import com.dp.io.ESN;
import com.dp.config.TimingHd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author LLF
 * @Date Created in 2022/3/26 14:30
 * @Description
 * @Version 2.0
 **/
@Component
@EnableAsync
public class HdTimeTakeSimple {


    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    RedisTemplate redisTemplate;



    //查询计划
    @Async
    public List<Map<String, Object>> plan(String types, String rules) {
        //A:当前时间 + 1.3小时 = 推送截至时间
        //B:上次推送时间 + 时间间隔 = 下次应该推送时间
        //if ： A > B  then  推送, 推送时间小，说明应该在这个时间点推送
        //if ： A < B  then  不推送，推送时间大，说明还没有到应该推送的时候
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nextTime = "";

//        String sql = " SELECT * from (SELECT id, UNAMELIST, UID, UPDATE_DATE, HECK_CYCL, WORK_TYPE, DATE_ADD( UPDATE_DATE, INTERVAL HECK_CYCL ";
//        //查出某天要下发哪些任务
//        switch (types){
//            case "小时":
//                calendar.add(Calendar.MINUTE, 10);//容错时间20分钟
//                nextTime = sdf.format(calendar.getTime());
//                if (rules.equals("odd")){
//                    sql += " hour) iftime FROM hd_check_plain WHERE DELETED = '0' AND HECK_CYCL%2 != 0 AND CHECK_CYCLE_UNIT = '小时' AND IFSTAR = '0' AND HECK_CYCL != 0 ) aa where aa.iftime < '"+ nextTime +"' ";
//                }else {
//                    sql += " hour) iftime FROM hd_check_plain WHERE DELETED = '0' AND HECK_CYCL%2 = 0 AND CHECK_CYCLE_UNIT = '小时' AND IFSTAR = '0' AND HECK_CYCL != 0 ) aa where aa.iftime < '"+ nextTime +"' ";
//                }
//                break;
//            case "天":
//                calendar.add(Calendar.HOUR_OF_DAY, 2);//容错时间2小时
//                nextTime = sdf.format(calendar.getTime());
//                sql += " day) iftime FROM hd_check_plain WHERE DELETED = '0' AND CHECK_CYCLE_UNIT = '天' AND IFSTAR = '0' AND HECK_CYCL != 0 ) aa where aa.iftime < '"+ nextTime +"' ";
//                break;
//            case "月":
//                calendar.add(Calendar.DATE, 5);//容错时间5天
//                nextTime = sdf.format(calendar.getTime());
//                sql += " month) iftime FROM hd_check_plain WHERE DELETED = '0' AND CHECK_CYCLE_UNIT = '月' AND IFSTAR = '0' AND HECK_CYCL != 0 ) aa where aa.iftime < '"+ nextTime +"' ";
//                break;
//            case "年":
//                calendar.add(Calendar.DATE, 10);//容错时间10天
//                nextTime = sdf.format(calendar.getTime());
//                sql += " year) iftime FROM hd_check_plain WHERE DELETED = '0' AND CHECK_CYCLE_UNIT = '年' AND IFSTAR = '0' AND HECK_CYCL != 0 ) aa where aa.iftime < '"+ nextTime +"' ";
//                break;
//            case "包保任务":
//                int day = calendar.get(Calendar.DAY_OF_MONTH);
//                int month = calendar.get(Calendar.MONTH) + 1;
//                sql = " SELECT id, UNAMELIST, UID, UPDATE_DATE, HECK_CYCL, WORK_TYPE, CHECK_CYCLE_UNIT FROM hd_check_plain WHERE DELETED = '0' and ( 1=1 ";
//                if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {//若为周一
//                    sql += " OR WORK_TYPE = '3' ";
//                }
//                if ( day ==1 && (month == 1 || month == 4 || month == 7 || month == 10 )) {//若为季度开始月
//                    sql += " OR WORK_TYPE = '2' ";
//                }
//                if (day ==1 && (month == 1 || month == 7)) {//若为半年开始月
//                    sql += " OR WORK_TYPE = '1' ";
//                }
//                sql += " ) ";
//                break;
//        }

        String sql = " SELECT * FROM hd_check_plain WHERE WORK_TYPE = '1' or WORK_TYPE = '2' or WORK_TYPE = '3' and DELETED = '0' ";

        List<Map<String, Object>> planList = jdbcTemplate.queryForList(sql);
        return planList;

    }





    /*
     * 查出这个点上班的人
     * */
    @Async
    public List<Map<String, Object>> onduty() {
        //查出来，在日期内上班的人信息
        List<Map<String, Object>> ondutyList = jdbcTemplate.queryForList(" " +
                " SELECT onduty.*, a.nickname, c.job_name, e.dep_name " +
                " FROM ( " +
                "   SELECT a.id, a.mid, a.createtime, a.STATUS, a.mpeopleid trueid, " +
                "       IF( a.STATUS = '1', b.did, a.mpeopleid ) mpeopleid, " +
                "       IF( a.STATUS = '1', b.ostime, a.startTime ) startTime, " +
                "       IF( a.STATUS = '1', b.oetime, a.endTime ) endTime" +
                "   FROM" +
                "       onduty_schedule a" +
                "       LEFT JOIN onduty_schedule_out b ON a.id = b.sid" +
                "   WHERE " +
                "       isdelete = '0' " +
                "       AND NOW() BETWEEN a.startTime AND a.endTime  " +
                "      ) onduty " +
                " LEFT JOIN sys_user a ON a.id = onduty.mpeopleid " +
                " LEFT JOIN sys_jobs_user b ON onduty.mpeopleid = b.user_id " +
                " LEFT JOIN sys_jobs c ON c.job_id = b.job_id " +
                " LEFT JOIN sys_department_user d ON d.user_id = onduty.mpeopleid " +
                " LEFT JOIN sys_department e ON e.dep_id = d.dep_id ");
        System.out.println(new Date().getTime());
        return ondutyList;
    }





    //    @Async
//    @PostConstruct
//    @Scheduled(cron = "0 1 1,3,5,7,9,11,13,15,17,19,21,23 * * ?")
    public void taskHourOdd(){
        System.out.println("进入-----------------------------------------------------------------------------------------" + new Date());
        List<Map<String, Object>> onduty = onduty();
        System.out.println("查询出值班-----------------------------------------------------------------------------------------" + new Date());
        List<Map<String,Object>> lc = new ArrayList<>();
        List<Map<String,Object>> list = plan("小时","odd");
        System.out.println("查询出计划-----------------------------------------------------------------------------------------" + new Date());
        for(Map<String,Object> map:list){
            List<String> ls = Arrays.asList(map.get("UID").toString().split(","));
            String SUID = "";
            String DNAME = "";
            String PNAME = "";
            String UNAME = "";
            for (int i = 0; i < ls.size(); i++) {
                if (!ls.get(i).equals("无此人") && !"".equals(ls.get(i))) {
                    String mpeopleid =  ls.get(i);
                    Optional<Map<String, Object>> foundItem = onduty.stream().filter(map1 -> mpeopleid.equals(map1.get("trueid"))).findAny();
                    if (foundItem.isPresent()) {
                        Map<String, Object> item = foundItem.get();
                        if (SUID.equals("")) {
                            SUID += item.get("mpeopleid");
                            DNAME += item.get("dep_name");
                            PNAME += item.get("job_name");
                            UNAME += item.get("nickname");
                        } else {
                            SUID += "," + item.get("mpeopleid");
                            DNAME += "," + item.get("dep_name");
                            PNAME += "," + item.get("job_name");
                            UNAME += "," + item.get("nickname");
                        }
                    }
                }
            }
            if (SUID != null && !"".equals(SUID) && !SUID.equals("null")) {
                map.put("UID", SUID.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("DNAME", DNAME.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("PNAME", PNAME.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("UNAME", UNAME.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("createtime", TimingHd.getDate());
                map.put("endtime", TimingHd.dateAdd(Integer.parseInt(map.get("HECK_CYCL").toString()),"小时"));
                if (map.get("WORK_TYPE").toString().equals("0")) {
                    map.put("IS_DEFEND", "0");
                } else {
                    map.put("IS_DEFEND", "1");
                }
                lc.add(map);
            }
        }
        System.out.println("整理完成" + new Date());
        if(lc.size() > 0){
            System.out.println("插入数据-----------------------------------------------------------------------------------------" + new Date());
            addPcRw1(lc);
            System.out.println("插入结束-----------------------------------------------------------------------------------------" + new Date());
        }
    }

    //    @Async
//    @PostConstruct
//    @Scheduled(cron = "0 1 0,2,4,6,8,10,12,14,16,18,20,22 * * ?")
    public void taskHourEven(){
        System.out.println("进入-----------------------------------------------------------------------------------------" + new Date());
        List<Map<String, Object>> onduty = onduty();
        System.out.println("查询出值班-----------------------------------------------------------------------------------------" + new Date());
        List<Map<String,Object>> lc = new ArrayList<>();
        List<Map<String,Object>> list = plan("小时","even");
        System.out.println("查询出计划-----------------------------------------------------------------------------------------" + new Date());
        for(Map<String,Object> map:list){
            List<String> ls = Arrays.asList(map.get("UID").toString().split(","));
            String SUID = "";
            String DNAME = "";
            String PNAME = "";
            String UNAME = "";
            for (int i = 0; i < ls.size(); i++) {
                if (!ls.get(i).equals("无此人") && !"".equals(ls.get(i))) {
                    String mpeopleid =  ls.get(i);
                    Optional<Map<String, Object>> foundItem = onduty.stream().filter(map1 -> mpeopleid.equals(map1.get("trueid"))).findAny();
                    if (foundItem.isPresent()) {
                        Map<String, Object> item = foundItem.get();
                        if (SUID.equals("")) {
                            SUID += item.get("mpeopleid");
                            DNAME += item.get("dep_name");
                            PNAME += item.get("job_name");
                            UNAME += item.get("nickname");
                        } else {
                            SUID += "," + item.get("mpeopleid");
                            DNAME += "," + item.get("dep_name");
                            PNAME += "," + item.get("job_name");
                            UNAME += "," + item.get("nickname");
                        }
                    }
                }
            }
            if (SUID != null && !"".equals(SUID) && !SUID.equals("null")) {
                map.put("UID", SUID.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("DNAME", DNAME.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("PNAME", PNAME.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("UNAME", UNAME.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("createtime", TimingHd.getDate());
                map.put("endtime", TimingHd.dateAdd(Integer.parseInt(map.get("HECK_CYCL").toString()),"小时"));
                if (map.get("WORK_TYPE").toString().equals("0")) {
                    map.put("IS_DEFEND", "0");
                } else {
                    map.put("IS_DEFEND", "1");
                }
                lc.add(map);
            }
        }
        System.out.println("整理完成" + new Date());
        if(lc.size() > 0){
            System.out.println("插入数据-----------------------------------------------------------------------------------------" + new Date());
            addPcRw1(lc);
            System.out.println("插入结束-----------------------------------------------------------------------------------------" + new Date());
        }
    }

    //    @Async
//    @Scheduled(cron = "0 1 8 * * ?")
    public void taskDay(){
        System.out.println("进入-----------------------------------------------------------------------------------------" + new Date());
        List<Map<String, Object>> onduty = onduty();
        System.out.println("查询出值班-----------------------------------------------------------------------------------------" + new Date());
        List<Map<String,Object>> lc = new ArrayList<>();
        List<Map<String,Object>> list = plan("天","dayly");
        System.out.println("查询出计划-----------------------------------------------------------------------------------------" + new Date());
        for(Map<String,Object> map:list){
            List<String> ls = Arrays.asList(map.get("UID").toString().split(","));
            String SUID = "";
            String DNAME = "";
            String PNAME = "";
            String UNAME = "";
            for (int i = 0; i < ls.size(); i++) {
                if (!ls.get(i).equals("无此人") && !"".equals(ls.get(i))) {
                    String mpeopleid =  ls.get(i);
                    Optional<Map<String, Object>> foundItem = onduty.stream().filter(map1 -> mpeopleid.equals(map1.get("trueid"))).findAny();
                    if (foundItem.isPresent()) {
                        Map<String, Object> item = foundItem.get();
                        if (SUID.equals("")) {
                            SUID += item.get("mpeopleid");
                            DNAME += item.get("dep_name");
                            PNAME += item.get("job_name");
                            UNAME += item.get("nickname");
                        } else {
                            SUID += "," + item.get("mpeopleid");
                            DNAME += "," + item.get("dep_name");
                            PNAME += "," + item.get("job_name");
                            UNAME += "," + item.get("nickname");
                        }
                    }
                }
            }
            if (SUID != null && !"".equals(SUID) && !SUID.equals("null")) {
                map.put("UID", SUID.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("DNAME", DNAME.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("PNAME", PNAME.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("UNAME", UNAME.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("createtime", TimingHd.getDate());
                map.put("endtime", TimingHd.dateAdd(Integer.parseInt(map.get("HECK_CYCL").toString()),"天"));
                if (map.get("WORK_TYPE").toString().equals("0")) {
                    map.put("IS_DEFEND", "0");
                } else {
                    map.put("IS_DEFEND", "1");
                }
                lc.add(map);
            }
        }
        System.out.println("整理完成" + new Date());
        if(lc.size() > 0){
            System.out.println("插入数据-----------------------------------------------------------------------------------------" + new Date());
            addPcRw1(lc);
            System.out.println("插入结束-----------------------------------------------------------------------------------------" + new Date());
        }
    }


    //    @Async
//    @Scheduled(cron = "0 1 8 1 * ?")
    public void taskMonth(){
        System.out.println("进入-----------------------------------------------------------------------------------------" + new Date());
        List<Map<String, Object>> onduty = onduty();
        System.out.println("查询出值班-----------------------------------------------------------------------------------------" + new Date());
        List<Map<String,Object>> lc = new ArrayList<>();
        List<Map<String,Object>> list = plan("月","string");
        System.out.println("查询出计划-----------------------------------------------------------------------------------------" + new Date());
        for(Map<String,Object> map:list){
            List<String> ls = Arrays.asList(map.get("UID").toString().split(","));
            String SUID = "";
            String DNAME = "";
            String PNAME = "";
            String UNAME = "";
            for (int i = 0; i < ls.size(); i++) {
                if (!ls.get(i).equals("无此人") && !"".equals(ls.get(i))) {
                    String mpeopleid =  ls.get(i);
                    Optional<Map<String, Object>> foundItem = onduty.stream().filter(map1 -> mpeopleid.equals(map1.get("trueid"))).findAny();
                    if (foundItem.isPresent()) {
                        Map<String, Object> item = foundItem.get();
                        if (SUID.equals("")) {
                            SUID += item.get("mpeopleid");
                            DNAME += item.get("dep_name");
                            PNAME += item.get("job_name");
                            UNAME += item.get("nickname");
                        } else {
                            SUID += "," + item.get("mpeopleid");
                            DNAME += "," + item.get("dep_name");
                            PNAME += "," + item.get("job_name");
                            UNAME += "," + item.get("nickname");
                        }
                    }
                }
            }
            if (SUID != null && !"".equals(SUID) && !SUID.equals("null")) {
                map.put("UID", SUID.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("DNAME", DNAME.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("PNAME", PNAME.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("UNAME", UNAME.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("createtime", TimingHd.getDate());
                map.put("endtime", TimingHd.dateAdd(Integer.parseInt(map.get("HECK_CYCL").toString()),"月"));
                if (map.get("WORK_TYPE").toString().equals("0")) {
                    map.put("IS_DEFEND", "0");
                } else {
                    map.put("IS_DEFEND", "1");
                }
                lc.add(map);
            }
        }
        System.out.println("整理完成" + new Date());
        if(lc.size() > 0){
            System.out.println("插入数据-----------------------------------------------------------------------------------------" + new Date());
            addPcRw1(lc);
            System.out.println("插入结束-----------------------------------------------------------------------------------------" + new Date());
        }
    }



    //    @Async
//    @Scheduled(cron = "0 1 8 1 1 ?")
    public void taskYear(){
        System.out.println("进入-----------------------------------------------------------------------------------------" + new Date());
        List<Map<String, Object>> onduty = onduty();
        System.out.println("查询出值班-----------------------------------------------------------------------------------------" + new Date());
        List<Map<String,Object>> lc = new ArrayList<>();
        List<Map<String,Object>> list = plan("年","string");
        System.out.println("查询出计划-----------------------------------------------------------------------------------------" + new Date());
        for(Map<String,Object> map:list){
            List<String> ls = Arrays.asList(map.get("UID").toString().split(","));
            String SUID = "";
            String DNAME = "";
            String PNAME = "";
            String UNAME = "";
            for (int i = 0; i < ls.size(); i++) {
                if (!ls.get(i).equals("无此人") && !"".equals(ls.get(i))) {
                    String mpeopleid =  ls.get(i);
                    Optional<Map<String, Object>> foundItem = onduty.stream().filter(map1 -> mpeopleid.equals(map1.get("trueid"))).findAny();
                    if (foundItem.isPresent()) {
                        Map<String, Object> item = foundItem.get();
                        if (SUID.equals("")) {
                            SUID += item.get("mpeopleid");
                            DNAME += item.get("dep_name");
                            PNAME += item.get("job_name");
                            UNAME += item.get("nickname");
                        } else {
                            SUID += "," + item.get("mpeopleid");
                            DNAME += "," + item.get("dep_name");
                            PNAME += "," + item.get("job_name");
                            UNAME += "," + item.get("nickname");
                        }
                    }
                }
            }
            if (SUID != null && !"".equals(SUID) && !SUID.equals("null")) {
                map.put("UID", SUID.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("DNAME", DNAME.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("PNAME", PNAME.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("UNAME", UNAME.replaceAll(",null", "").replaceAll("null,", ""));
                map.put("createtime", TimingHd.getDate());
                map.put("endtime", TimingHd.dateAdd(Integer.parseInt(map.get("HECK_CYCL").toString()),"年"));
                if (map.get("WORK_TYPE").toString().equals("0")) {
                    map.put("IS_DEFEND", "0");
                } else {
                    map.put("IS_DEFEND", "1");
                }
                lc.add(map);
            }
        }
        System.out.println("整理完成" + new Date());
        if(lc.size() > 0){
            System.out.println("插入数据-----------------------------------------------------------------------------------------" + new Date());
            addPcRw1(lc);
            System.out.println("插入结束-----------------------------------------------------------------------------------------" + new Date());
        }
    }


    @Async
//    @PostConstruct
//    @Scheduled(cron = "0 1 0 * * ?")
    //包保任务
    public void taskBBRW(){
        System.out.println("进入-----------------------------------------------------------------------------------------------" + new Date());
        List<Map<String,Object>> lc = new ArrayList<>();
        List<Map<String,Object>> list = plan("包保任务","string");
        System.out.println("查询出计划------------------------------------------------------------------------------------------" + new Date());
        for(Map<String,Object> map:list){
            map.put("createtime", TimingHd.getDate());
            map.put("endtime", TimingHd.dateAdd(Integer.parseInt(map.get("HECK_CYCL").toString()),map.get("CHECK_CYCLE_UNIT").toString()));
            map.put("IS_DEFEND", "1");
            lc.add(map);
        }
        if(lc.size() > 0){
            System.out.println("插入数据-----------------------------------------------------------------------------------------" + new Date());
            addPcRw1(lc);
            System.out.println("插入结束-----------------------------------------------------------------------------------------" + new Date());
        }
    }


    public void addPcRw1(List<Map<String,Object>> list) {
        if (list.size() > 0){
            StringBuilder stringBuilder = new StringBuilder();
            StringBuilder ids = new StringBuilder();
            list.forEach(map -> {
                stringBuilder.append("('" + ESN.getUUID() + "','" + map.get("ID").toString() + "','0','0','"+map.get("DNAME")+"','"+map.get("PNAME")+"','"+map.get("UNAME")+"','" + map.get("UID") + "','"+map.get("createtime")+"','"+map.get("createtime")+"','" + map.get("endtime")+ "','"+map.get("IS_DEFEND")+"'),");
                ids.append("'").append(map.get("ID").toString()).append("'").append(",");
                StringBuilder stringBuilder1 = new StringBuilder();
                StringBuilder stringBuilder2 = new StringBuilder();
                stringBuilder1.append("INSERT INTO sys_message (message_id,message_title,message_content,message_sender,message_senderid,create_time, update_time,message_status) VALUE ");
                stringBuilder2.append("INSERT INTO sys_user_message (id,user_id,message_id,isread) VALUE ");
                Arrays.asList(map.get("UID").toString().split(",")).forEach(item -> {
                    String uuid = ESN.getUUID();
                    stringBuilder1.append("( '" + uuid + "', '隐患排查任务推送','您有一条新的隐患排查任务推送','系统', '733914f8-3435-4e35-b02e-d51fbc1b5cc1',now(),now(),'1'),");
                    stringBuilder2.append("( '" + ESN.getUUID() + "','" + item + "', '" + uuid + "','0'),");
                });
                jdbcTemplate.execute(stringBuilder1.substring(0,stringBuilder1.length()-1));
                jdbcTemplate.execute(stringBuilder2.substring(0,stringBuilder2.length()-1));
            });
            StringBuilder sql = new StringBuilder();
            sql.append("INSERT INTO hd_check_task (RWID,PID,OVERDUECOUNT,STATUS,DNAME,PNAME,UNAME,USERID,INVESTIGATION_DATE,CREATE_DATE,endtime,IS_DEFEND)VALUE ").append(stringBuilder.substring(0, stringBuilder.length() - 1));
            jdbcTemplate.batchUpdate(sql.toString());
            jdbcTemplate.batchUpdate("update hd_check_plain set UPDATE_DATE = '"+list.get(0).get("createtime")+"',HECK_STATUS = '0' where ID in (" + ids.substring(0, ids.length() - 1) + ")");
        }
    }








}
